package com.bjsxt.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;

        Object student = req.getSession().getAttribute("admin");

        String requestURI = req.getRequestURI();
        if ("/ty/login.jsp".equals(requestURI)||"/ty/MyController/findStudent".equals(requestURI)){
            filterChain.doFilter(req,resp);
            return;
        }

        if (student!=null){
            filterChain.doFilter(req,resp);
        }else {

            if("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))){
                System.out.println("ajax中Session跳转页面");
                resp.setHeader("sessionstatus", "timeout");
                resp.setHeader("redirectUrl", "/ty/login.jsp");
            } else {
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
